package com.sikong.geotools.simple;

import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.filter.text.cql2.CQL;
import org.geotools.filter.text.cql2.CQLException;
import org.opengis.filter.Filter;

import java.io.File;
import java.io.IOException;

/**
 * 这是一段用于简单使用CQL语句查询要素的代码
 * 1、读取shp文件得到datastore
 * 2、通过datastore得到featureSource
 * 3、输入CQL表达式转为Filter
 * 4、将Filter输入至featureSource
 *
 * @author 梁超 / stan
 * @since 0.1.0
 * @Date 2022/03/25
 */
public class FeatureQuery {

    /**
     * 读取shp文件，获得featureSource
     *
     * @return featureSource
     */
    public SimpleFeatureSource readShp(String file) throws IOException {
        FileDataStore dataStore = FileDataStoreFinder.getDataStore(new File(file));
        SimpleFeatureSource featureSource = dataStore.getFeatureSource();

        return featureSource;
    }

    /**
     * 执行CQL表达式查询，得到查询结果
     *
     * @param featureSource 读取shp获得到的featureSource
     * @return featureCollection
     */
    public SimpleFeatureCollection queryShp(SimpleFeatureSource featureSource,String cqlPredicate) throws CQLException, IOException {

        Filter filter = CQL.toFilter(cqlPredicate);
        SimpleFeatureCollection featureCollection = featureSource.getFeatures(filter);

        return featureCollection;
    }
}
